<template>
  <div class="left_tree_area">
    <!-- 顶部标题区 -->
    <div class="tree_title">
      <div class="left_title">
        <div class="left_icon">
          <!-- 左侧图标 -->
          <svg-icon :icon-class="iconName"></svg-icon>
        </div>
        <div>{{ title }}</div>
      </div>
      <div class="right_btn">
        <!-- 插槽：右侧标题按钮 -->
        <slot name="titleBTn"></slot>
      </div>
    </div>

    <div class="gray_back"></div>

    <!-- 树形结构展示 -->
    <el-tree
      ref="leftTreeSelectRef"
      v-if="treeData.length > 0"
      :indent="20"
      highlight-current
      class="tree_main"
      :data="treeData"
      :props="treeProps"
      :node-key="nodeKeyField"
      default-expand-all
      :show-checkbox="showCheckbox"
      :default-checked-keys="defaultCheckIds"
      :expand-on-click-node="false"
      @check-change="handleCheckChange"
      @check="handleChecked"
      :check-strictly="checkStrictly"
      @node-click="handleNodeClick"
      :check-on-click-node="canClickToCheck"
    >
      <!-- 自定义节点渲染插槽 -->
      <template slot-scope="{ node, data }">
        <div class="custom-tree-node">
          <div>{{ node.label }}</div>

          <!-- 右侧按钮 -->
          <div
            class="right_btn"
            v-if="
              needRightBtn &&
              selectOption[selectProps.value] === data[selectProps.value]
            "
          >
            <div
              v-for="btn in customButtons"
              :key="btn.title"
              :title="btn.title"
              :class="btn.class"
              @click="btn.action(node, data)"
            >
              <template v-if="shouldShowButton(btn.title, data)">
                <el-icon><component :is="btn.icon" /></el-icon>
              </template>
            </div>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script>
export default {
  name: "LeftTreeArea",
  // 接收父组件传递的 props
  props: {
    title: {
      type: String,
      default: "树形结构",
    },
    iconName: {
      type: String,
      default: "organizationManagement",
    },
    needRightBtn: {
      type: Boolean,
      default: false,
    },
    // 控制特定按钮是否显示
    rightBtnCondition: {
      type: Object,
      default: () => ({}),
    },
    treeData: {
      type: Array,
      default: () => [],
      required: true,
    },
    showCheckbox: {
      type: Boolean,
      default: false,
    },
    defaultCheckIds: {
      type: Array,
      default: () => [],
    },
    treeProps: {
      type: Object,
      default: () => ({
        children: "children",
        label: "label",
      }),
    },
    nodeKeyField: {
      type: String,
      required: true,
    },
    onNodeClick: {
      type: Function,
      default: () => {},
    },
    customButtons: {
      type: Array,
      default: () => [],
    },
    selectOption: {
      type: Object,
      default: () => ({}),
    },
    selectProps: {
      type: Object,
      default: () => ({
        children: "children",
        label: "Label",
        value: "value",
      }),
    },
    // 是否父子节点不关联选择
    isCheckStrictly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 控制 check-strictly 行为（父子不联动）
      checkStrictly: this.isCheckStrictly,
    };
  },
  computed: {
    // 是否点击节点也选中复选框
    canClickToCheck() {
      return this.showCheckbox ? true : false;
    },
  },
  watch: {
    // 当 treeData 变化后设置默认选中项
    treeData(newVal) {
      if (this.$refs.leftTreeSelectRef && newVal.length > 0) {
        this.$refs.leftTreeSelectRef.setCheckedKeys(this.defaultCheckIds);
      }
    },
  },
  mounted() {
    // 组件挂载后默认设置选中节点
    this.$nextTick(() => {
      if (this.$refs.leftTreeSelectRef && this.treeData.length > 0) {
        this.$refs.leftTreeSelectRef.setCheckedKeys(this.defaultCheckIds);
      }
    });
  },
  methods: {
    // 判断某个按钮是否应该显示（可配置）
    shouldShowButton(title, data) {
      return this.rightBtnCondition[title]
        ? this.rightBtnCondition[title](data)
        : true;
    },
    // 当点击树的复选框时触发
    handleChecked() {
      console.log("checkStrictly 状态：", this.checkStrictly);
      if (this.checkStrictly) {
        // 重置 checkStrictly 状态为 false
        this.$nextTick(() => {
          this.checkStrictly = false;
        });
      }
    },
    // 节点点击事件，通知父组件
    handleNodeClick(e) {
      this.$emit("handleNodeClick", e);
    },
    // 复选框状态变化处理逻辑
    handleCheckChange(node, checked) {
      const selectedValues = this.$refs.leftTreeSelectRef.getCheckedKeys(); // 全选值
      const halfCheckedNodes =
        this.$refs.leftTreeSelectRef.getHalfCheckedNodes(); // 半选节点

      // 递归查找已选节点对象（可选：过滤 ranks === 0）
      const findNodesByValue = (data, values, filterRanks = false) => {
        let result = [];
        data.forEach((item) => {
          if (
            values.includes(item.value) &&
            (!filterRanks || item.ranks !== 0)
          ) {
            result.push(item);
          }
          if (item.children && item.children.length) {
            result = result.concat(
              findNodesByValue(item.children, values, filterRanks)
            );
          }
        });
        return result;
      };

      const selectedNodes = findNodesByValue(this.treeData, selectedValues);
      const halfCheckedNodesArray = findNodesByValue(
        this.treeData,
        halfCheckedNodes.map((node) => node.value),
        true
      );

      const allSelectedNodes = [...selectedNodes, ...halfCheckedNodesArray];
      // 发出完整选择节点数组
      this.$emit("handleCheckChange", allSelectedNodes);
    },
  },
};
</script>

<style scoped></style>
